package com.tuanzi.blog.service.impl;

import com.tuanzi.blog.NotFoundException;
import com.tuanzi.blog.dao.TagMapper;
import com.tuanzi.blog.model.Tag;
import com.tuanzi.blog.model.Type;
import com.tuanzi.blog.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 雄关漫道真如铁，而今迈过从头越
 **/

@Service
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;

    /**
     * 保存新的标签到t_tag中
     * 1.插入成功
     * 2.插入失败
     * 3.数据库中已经有了
     */
    @Transactional
    @Override
    public int saveTag(Tag tag) {
        if (tagMapper.selectByName(tag.getName()) == null){
            if (tagMapper.insert(tag) == 1){
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        Tag tag = tagMapper.selectByPrimaryKey(id);
        return tag;
    }

    /**
     * 获取所有的Tag标签
     * @return
     */
    @Transactional
    @Override
    public List<Tag> getAllTags() {
        List<Tag> tags = tagMapper.selectAllTagInfo();
        return tags;
    }

    /**
     * 1.更新成功
     * 2.更新失败
     * 3.数据库中已经有了
     */
    @Transactional
    @Override
    public int updateTag(Long id, Tag tag) {
        Tag t = tagMapper.selectByPrimaryKey(id);
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }else {
            if (t.getName().equals(tag.getName())){
                return 3;
            }
            BeanUtils.copyProperties(tag,t);
            if (tagMapper.updateByPrimaryKey(tag) != 0){
                return 1;
            }
            return 2;
        }
    }

    @Transactional
    @Override
    public Tag deleteTag(Long id) {
        Tag tag = tagMapper.selectByPrimaryKey(id);
        int i = tagMapper.deleteByPrimaryKey(id);
        if (i == 1){
            return tag;
        }else{
            return null;
        }
    }
}
